const express = require('express');
var router = express.Router();
// eslint-disable-next-line no-unused-vars
const tools = require('../../model/tools')
const NavModel = require('../../model/navModel')

router.get("/",(req,res)=>{
  //获取表单数据
  NavModel.find({},(err,data)=>{
    if(err){
      console.log(err);
      return;
    }
    res.render("admin/nav/index.html",{
      list:data
    });
  })
 
})

//渲染添加导航页面
router.get("/add",(req,res)=>{
  res.render("admin/nav/add.html")
})

//增加导航
router.post("/doAdd",(req,res)=>{
  //获取表单数据
  let {title,link,position,is_opennew,sort,status} = req.body;

  var result =new NavModel({
    title,
    link,
    position,
    is_opennew,
    sort,
    status,
    add_time:tools.getUnix()
  })
  result.save((err)=>{
    if(err){
      console.log(err);
      return;
    }else{
      res.render("admin/public/success.html",{
        redirectUrl:`/${req.app.locals.adminPath}/nav`,
        message:"添加成功"
      });
    }
  })
})

//导航数据回显
router.get("/edit",(req,res)=>{
  //获取要修改的导航id
  let {id} = req.query;
  NavModel.find({_id:id},(err,data)=>{
    if(err){
      console.log(err);
      return;
    }
    if(data.length>0){
      res.render("admin/nav/edit.html",{
        list:data[0]
      });
    }else{
      res.redirect(`/${req.app.locals.adminPath}/nav`);
    }
 
  })

})

//修改导航逻辑
router.post("/doEdit",(req,res)=>{
  //获取表单数据
  let {id,title,link,position,is_opennew,sort,status} = req.body;
  NavModel.updateOne({_id:id},{
    title,
    link,
    position,
    is_opennew,
    sort,
    status
    },(err)=>{
      if(err){
        console.log(err);
        return;
      }
      res.render("admin/public/success.html",{
        redirectUrl:`/${req.app.locals.adminPath}/nav`,
        message:"修改成功"
      });
    })
})


//删除导航

//删除管理员
router.get("/delete",(req,res)=>{
  //获取要删除的管理员id
  let {id} = req.query;
  NavModel.deleteOne({_id:id},(err)=>{
    if(err){
      console.log(err);
      return;
    }
    res.render("admin/public/success.html",{
			redirectUrl:`/${req.app.locals.adminPath}/nav`,
			message:"删除成功"
		})
  })

})

module.exports = router